package service;

import dao.BookDao;
import dao.BooklossDao;
import domin.Book;
import domin.Bookloss;
import util.Condition;
import util.JdbcHelper;
import util.Pagination;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Collection;
import java.util.HashSet;

public class BooklossService {
    private BooklossDao booklossDao = BooklossDao.getInstance();
    private static BooklossService booklossService = new BooklossService();
    public static BooklossService getInstance(){
        return  booklossService;
    }

    public Collection<Bookloss> findAll(Collection<Condition> condition, Pagination pagination) throws SQLException {
        Connection connection = JdbcHelper.getConn();
        Collection<Bookloss> booklosses = booklossDao.findAll(connection,condition,pagination);
        JdbcHelper.close(connection);
        return booklosses;
    }

    public Bookloss find(Integer id) throws SQLException {
        Connection connection = JdbcHelper.getConn();
        Bookloss bookloss = booklossDao.find(connection,id);
        JdbcHelper.close(connection);
        return bookloss;
    }
    public boolean update(Bookloss bookloss) throws SQLException {
        Connection connection = JdbcHelper.getConn();
        connection.setAutoCommit(false);
        boolean updated = false;
        try{
            updated = booklossDao.update(connection,bookloss);
            connection.commit();
        }
        catch (SQLException e){
            connection.rollback();
        }
        finally {
            connection.setAutoCommit(true);
            JdbcHelper.close(connection);
        }
        return updated;
    }

    public boolean add(Bookloss bookloss) throws SQLException {
        Connection connection = JdbcHelper.getConn();
        connection.setAutoCommit(false);
        boolean added = false;
        try{
            added = booklossDao.add(connection,bookloss);
            connection.commit();
        }
        catch (SQLException e){
            connection.rollback();
        }
        finally {
            connection.setAutoCommit(true);
            JdbcHelper.close(connection);
        }
        return added;
    }


    public boolean delete(Integer id) throws SQLException {
        Connection connection = JdbcHelper.getConn();
        System.out.println(5);
        boolean deleted =booklossDao.delete(connection,id);
        JdbcHelper.close(connection);
        return deleted;
    }
}
